package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vo.ScrollResultVO;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;
    
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询所有博客，并判断当前博客是否被当前用户点赞
        records.forEach(blog -> {
            this.quertBlogUser(blog);
            this.isBologLiked( blog);
        });

        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //1、查询博客
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }

        //2、查询blog的作者
        quertBlogUser(blog);

        //3、查询该博客是否被点赞
        isBologLiked(blog);

        return Result.ok(blog);
    }

    /**
     * 查询当前博客是否已经被点赞
     * @param blog
     */
    private void isBologLiked(Blog blog) {
        //获取当前登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null)
        {
            //未登录也可以访问首页内容
            return;
        }

        //1、查询当前用户
        Long userId = UserHolder.getUser().getId();
        //2、查询当前用户是否已经点赞
        String key = BOLG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        //3、修改用户是否点赞状态
        blog.setIsLike(score!= null);
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //1。1查询当前用户
        Long userId = UserHolder.getUser().getId();
        //2、查询当前用户是否已经点赞
        String key = BOLG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score== null)//根据userId查询不到分数这说明当前用户没有点赞
        {
            //3、未点赞，
            //3.1，点赞数++
            boolean update = update().setSql("liked = liked + 1").eq("id", id).update();

            if (update)
            {
                //3.2，将当前用户id保存到Redis的scoreset集合中，zadd key + id + 当前时间戳
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }
        else {

            //4.已点赞
            //4.1，点赞数--
            boolean update = update().setSql("liked = liked - 1").eq("id", id).update();
            //4.2，将当前用户id从Redis的set集合中移除
            if (update)
            {
                //3.2，将当前用户id从Redis的set集合移除
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }

        }
        return Result.ok();
    }



    /**
     * 查询用户
     * 并封装博客作者基本 信息
     * @param blog
     */
    private void quertBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


    /**
     * 查询点赞用户
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        //1、查询top5的点赞用户 ：zrangs key 0 4
        String key = BOLG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);

        //1.1 判断
        if (top5 == null || top5.isEmpty())
            return Result.ok(Collections.emptyList());//返回空集合

        //2、解析出其中的用户id--
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());

        //2.1将ids凭借为字符串
        String idStr = StrUtil.join(",", ids);

        //3、根据用户ids查询用户---自定义使用mybatis plus自定义sql语句设计所需业务需求---WHERE id IN(5,1)ORDER BY FIELD(id,5,1)
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + idStr +")" ).list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());//搜集为集合


        //4、返回
        return Result.ok(userDTOS);
    }

    /**
     * 发布博客
     * @param blog
     * @return
     */
    @Transactional
    @Override
    public Result saveBlog(Blog blog) {
        //1 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2\ 保存探店博文
        boolean save = save(blog);
        if (!save)
        {
            return Result.fail("发布失败！");
        }
        //3、获取当前用户的所有粉丝 follow_user_id 字段是被关注人的id,当前用户的id为：blog.getId(),
        // 那么follow_user_id=blog.getId()就可以知道当前用户所有的粉丝
        QueryChainWrapper<Follow> fans = followService.query().eq("follow_user_id", blog.getUserId());
        if (fans.count() >= 0)
        {
            //4、推送笔记给当前用户的所有粉丝
            for (Follow follow : fans.list())
            {
                //4.1获取粉丝id
                Long FansUserId = follow.getUserId();
                String key = Feed_KEY + FansUserId;//集合：key
                //4.2将笔记id保存到粉丝的收件箱
                stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
            }

        }

        //5、返回id
        return Result.ok(blog.getId());
    }

    /**
     * 查询当前用户所关注的人的最新笔记
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1、获取当前用户
        Long usaerId = UserHolder.getUser().getId();
        //2查询当前用户的收件箱
        String key = Feed_KEY + usaerId;//集合：key

        //返回值类型是一个元组，里面包含两个数据：blogId，max
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
                .opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        //3非空判断
        if (typedTuples==null || typedTuples.isEmpty())
            return Result.ok();

        //4、解析数据：blogId，minTime，offset 返回给前端
        List<Long> ids = new ArrayList<>(typedTuples.size());//存放所关注的博客id(手动指定集合长度避免自动扩容降低效率)

        long minTime = 0;//每一页最小 时间
        int os = 1;//每页偏移量
        for (ZSetOperations.TypedTuple<String> Tuple : typedTuples)
        {
            //4.1获取blogId
            String value = Tuple.getValue();
            ids.add(Long.valueOf(value));
            //4.2、获取分数即时间戳
            long time = Tuple.getScore().longValue();
            if (time == minTime)
            {
                os++;
            }
            else {
                minTime = time;
                os = 1;
            }
        }

        //5、根据信箱中关注的博客id查询博客数据
        String idStr = StrUtil.join(",", ids);

        //5.1使用自定义查询保证数据顺序不变
        List<Blog> blogs = query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + idStr + ")").list();

        //5.2查询每一个博客数据
        for (Blog blog : blogs)
        {
            //5.3查询此博客数据信息
            quertBlogUser(blog);
            //5.4查询此博客数据是否被当前用户点赞
            isBologLiked(blog);
        }

        //6、封装为数据返回
        ScrollResultVO scrollResultVO = new ScrollResultVO();
        scrollResultVO.setList(blogs);//博客数据
        scrollResultVO.setOffset(os);//偏移量
        scrollResultVO.setMinTime(minTime);//当前页最小时间戳就是下一页最大时间戳--滚动查询
        return Result.ok(scrollResultVO);
    }

}
